import React from 'react';
import {useDispatch} from 'react-redux';
import {AppState, DeviceEventEmitter} from 'react-native';
import {
    UserDidChangedNotification,
    UserDidSigninedNotification,
    UserDidSignoutedNotification,
} from '../../base/constants';
import CodePush, {RemotePackage} from 'react-native-code-push';
import {userDidChanged, userDidSignIn, userDidSignOut} from '../../store/actions';
import TokenStorage from '../../utils/TokenStorage';
import ModalUpdating from './ModalUpdating.tsx';

const AppInitialization = () => {
    const dispatch = useDispatch();
    const currentAppState = React.useRef(AppState.currentState);
    const updaterRef = React.useRef<any>();
    const listeners = React.useRef<any[]>([]);
    const remotePackgeRef = React.useRef<RemotePackage | undefined>();

    const checkUpdate = () => {
        CodePush.allowRestart();
        CodePush.checkForUpdate().then((remotePackge) => {
            if (remotePackge) {
                remotePackgeRef.current = remotePackge;
                updaterRef.current?.open();
            }
        }).catch(error => {
            console.error(error.message);
        });
    };

    const downloadApp = React.useCallback(() => {
        updaterRef.current?.setUpdating(true);
        remotePackgeRef.current?.download(progress => {
            //Toast.info(`${progress.receivedBytes}/${progress.totalBytes}`);
            updaterRef.current?.setProgress(progress.receivedBytes / progress.totalBytes);
        }).then(localPackage => {
            setTimeout(() => {
                localPackage.install(CodePush.InstallMode.IMMEDIATE).then(() => {
                    updaterRef.current?.close();
                    CodePush.notifyAppReady();
                    CodePush.restartApp();
                }).catch(error => {
                    console.error(error.message);
                }).finally(() => {
                    updaterRef.current?.setUpdating(false);
                });
            }, 1500);
        }).catch(reason => {
            console.error(reason.message);
            updaterRef.current?.close();
        });
    }, [remotePackgeRef.current, updaterRef.current]);

    const addListeners = () => {
        listeners.current[0] = DeviceEventEmitter.addListener(UserDidSigninedNotification, () => {
            dispatch(userDidSignIn());
        });

        listeners.current[1] = DeviceEventEmitter.addListener(UserDidSignoutedNotification, () => {
            TokenStorage.removeToken();
            dispatch(userDidSignOut());
        });

        listeners.current[2] = DeviceEventEmitter.addListener(UserDidChangedNotification, userInfo => {
            dispatch(userDidChanged());
        });

        listeners.current[4] = AppState.addEventListener('change', (nextAppState) => {
            //console.log("AppState", currentAppState.current, nextAppState);
            if (currentAppState.current.match(/background/) && nextAppState === 'active') {
                //console.log("App has come to the foreground!");
                //checkUpdate();
                //echo.connect();
                if (!__DEV__) {
                    checkUpdate();
                }
            }
            currentAppState.current = nextAppState;
        });
    };

    const removeListeners = () => {
        listeners.current?.forEach((listener: any) => {
            listener.remove();
        });
    };

    React.useEffect(() => {
        addListeners();
        // const orderChannle = echo.channel('orders').listen('.pusher:subscription_succeeded', (e: any) => {
        //     console.log('pusher:subscription_succeeded');
        // }).listen('.order.created', (e: any) => {
        //     console.log('order.created', e);
        // });
        //
        // const posChannel = echo.channel('pos').listen('.pos.logout', (e: any) => {
        //     TokenStorage.removeToken().then(() => {
        //         dispatch(userDidSignOut());
        //     });
        // });

        if (!__DEV__) {
            checkUpdate();
        }

        return () => {
            //orderChannle.stopListeningToAll();
            //posChannel.stopListeningToAll();
            removeListeners();
        }
    }, []);

    return (
        <>
            <ModalUpdating
                ref={updaterRef}
                onPress={downloadApp}
            />
        </>
    );
};

export default AppInitialization;
